<template>
  <div class="container">

    <img
      :src="localDate"
      ref="img"
    >
    <div class="handle">
      <div
        class="cancel"
        @click="$emit('close')"
      >取消</div>
      <div
        class="comfirm"
        @click="upload"
      >完成</div>
    </div>
  </div>
</template>
<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { setUserPhoto } from '@/api/user.js'

export default {
  props: {
    value: {
      type: [String, Number],
      required: true,
      cropper: ''
    }
  },
  data () {
    return {
      localDate: this.value
    }
  },
  mounted () {
    const image = this.$refs.img
    const cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
    this.cropper = cropper
  },
  methods: {
    upload () {
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        const formData = new FormData()
        // Pass the image file name as the third parameter if necessary.
        formData.append('croppedImage', blob/*, 'example.png' */)
        const image = window.URL.createObjectURL(blob)
        try {
          await setUserPhoto(formData)
          this.$emit('upload', image)
          this.$emit('close')
          this.$toast.success('设置成功')
        } catch (err) {
          this.$toast.fail('设置失败')
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  background: #000;
  .handle {
    width: 100%;
    position: fixed;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    div {
      font-size: 30px;
      width: 100px;
      height: 100px;
      text-align: center;
      line-height: 100px;
      color: rgb(255, 255, 255);
    }
  }
}
</style>
